#include "stm32f10x.h"                  // Device header

unsigned int number=0;
unsigned long int times=0;

void HCSR04_init(void)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
	
	GPIO_InitTypeDef HCSR04_GPIO_initsturture;
	HCSR04_GPIO_initsturture.GPIO_Mode=GPIO_Mode_Out_PP;
	HCSR04_GPIO_initsturture.GPIO_Pin=GPIO_Pin_5;
	HCSR04_GPIO_initsturture.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&HCSR04_GPIO_initsturture);
	
	HCSR04_GPIO_initsturture.GPIO_Mode=GPIO_Mode_IN_FLOATING;
	HCSR04_GPIO_initsturture.GPIO_Pin=GPIO_Pin_4;
	HCSR04_GPIO_initsturture.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&HCSR04_GPIO_initsturture);
	
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOA,GPIO_PinSource4);
	EXTI_InitTypeDef HCSR04_EXTI_initsturcture;
	HCSR04_EXTI_initsturcture.EXTI_Line=EXTI_Line4;
	HCSR04_EXTI_initsturcture.EXTI_LineCmd=ENABLE;
	HCSR04_EXTI_initsturcture.EXTI_Mode=EXTI_Mode_Interrupt;
	HCSR04_EXTI_initsturcture.EXTI_Trigger=EXTI_Trigger_Rising_Falling;
	EXTI_Init(&HCSR04_EXTI_initsturcture);
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	
	NVIC_InitTypeDef HCSR04_NVIC_initstureture;
	HCSR04_NVIC_initstureture.NVIC_IRQChannel=EXTI4_IRQn;
	HCSR04_NVIC_initstureture.NVIC_IRQChannelCmd=ENABLE;
	HCSR04_NVIC_initstureture.NVIC_IRQChannelPreemptionPriority=1;
	HCSR04_NVIC_initstureture.NVIC_IRQChannelSubPriority=1;
	NVIC_Init(&HCSR04_NVIC_initstureture);
	
	
	TIM_TimeBaseInitTypeDef HCSR04_timsturecture;
	HCSR04_timsturecture.TIM_ClockDivision=TIM_CKD_DIV1;
	HCSR04_timsturecture.TIM_CounterMode=TIM_CounterMode_Up;
	HCSR04_timsturecture.TIM_Period=1000-1;
	HCSR04_timsturecture.TIM_Prescaler=72-1;
	HCSR04_timsturecture.TIM_RepetitionCounter=0;
	TIM_TimeBaseInit(TIM2,&HCSR04_timsturecture);
	TIM_InternalClockConfig(TIM2);
	
	HCSR04_NVIC_initstureture.NVIC_IRQChannel=TIM2_IRQn;
	HCSR04_NVIC_initstureture.NVIC_IRQChannelCmd=ENABLE;
	HCSR04_NVIC_initstureture.NVIC_IRQChannelPreemptionPriority=2;
	HCSR04_NVIC_initstureture.NVIC_IRQChannelSubPriority=2;
	NVIC_Init(&HCSR04_NVIC_initstureture);
	
	TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
	
	TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
	
}

void EXTI4_IRQHandler(void)
{
	
	if(EXTI_GetFlagStatus(EXTI_Line4)==SET)
	{	
		if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_4)==SET)
		{
			TIM_SetCounter(TIM2,0);
			number=0;
			times=0;
			TIM_Cmd(TIM2,ENABLE);
		}
		else if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_4)==RESET)
		{
			TIM_Cmd(TIM2,DISABLE);
			times=number*1000+TIM_GetCounter(TIM2);
		}
	}
	EXTI_ClearITPendingBit(EXTI_Line4);
}

void TIM2_IRQHandler(void)
{
	if(TIM_GetITStatus(TIM2,TIM_IT_Update)==SET)
	{
		number++;
	}
	TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
}

